# -*- coding: utf-8 -*-
# filename: basic.py
import urllib
import time
import json
import os

class Basic:
    def __init__(self):
        self.__accessToken = ''
        self.__leftTime = 0
        self.__filePath = "%s/static/appid_test.json" %(os.getcwd())
    
    def __real_get_access_token(self):
        #appId = "wx9993d09f56bcd5d6"
        #appSecret = "dcda67b6e2174293789b588485595b05"

        data = self.__get_appid_from_file()
        appId = data['appid']
        appSecret = data['secret']
        postUrl = ("https://api.weixin.qq.com/cgi-bin/token?grant_type="
               "client_credential&appid=%s&secret=%s" % (appId, appSecret))
        urlResp = urllib.urlopen(postUrl)
        urlResp = json.loads(urlResp.read())
        
        self.__accessToken = urlResp['access_token']
        self.__leftTime = urlResp['expires_in']

    def __get_appid_from_file(self):
        fdata = open(self.__filePath, "r+")
        data = json.load(fdata)
        print data
        return data

    def get_access_token(self):
        if self.__leftTime < 10:
            self.__real_get_access_token()
        print "LJF-> token:%s" %self.__accessToken
        return self.__accessToken

    def run(self):
        while(True):
            if self.__leftTime > 10:
                time.sleep(2)
                self.__leftTime -= 2
            else:
                self.__real_get_access_token()
